import * as PIXI from 'pixi.js';
import StageConf from '../../conf/StageConf';
import ScalerUtil from '../../util/ScalerUtil';
import PointView from './PointView';

export default class ShapeView extends PIXI.Sprite{
   
    points:PIXI.Point[] = [];
    container:PIXI.Container;
    pointViews:PointView[] = [];
    view:PIXI.Graphics;
    color:number;

    constructor(points:PIXI.Point[]){
        super();

        this.color = Math.floor(Math.random() * 0xffffff);

        this.view = new PIXI.Graphics();
        this.addChild(this.view);
        
        this.container = new PIXI.Container();
        this.addChild(this.container);

        this.init(points);
    }

    addPoint(p:any){
        this.addView(p, this.points.length);
        this.points.push(p);
        this.draw();
    }

    addView(item:any, index:number){
        var p = new PointView(this.color);
        p.id = index;
        p.x = item.x;
        p.y = item.y;
        p.interactive = true;
        p.on("pointerdown", this.trace);

        this.container.addChild(p);
        this.pointViews.push(p);
    }

    init(points:PIXI.Point[]){
        this.points = points;
        this.container.removeChildren();
        this.pointViews = [];

        this.points.forEach((item, index) => {
            this.addView(item, index);
        })
        this.draw();
    }

    clear(){
        this.view.clear();
        this.container.removeChildren();
        this.pointViews = [];
        this.points = [];
    }

    trace(e:any){
        e.stopPropagation();
        console.log(this.x, this.y);
    }

    draw(){
        this.view.clear();
        var weight = ScalerUtil.pxSize;
        this.view.lineStyle(weight, this.color, 0.4);
        // this.view.beginFill(this.color, 0.2);
        this.view.drawPolygon(this.points);
        this.view.endFill();
        this.pointViews.forEach(item => item.draw());
    }
    
}